package com.zf.flink.simple;

import com.alibaba.fastjson.JSON;
import com.zf.flink.User;
import com.zf.flink.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    public User findById(Long id) {
        String key = "user_cache";
        String field = id.toString();
        String json = redisTemplate.opsForHash().get(key, field).toString();
        if (json != null) {
            return JSON.parseObject(json, User.class);
        }
        // 缓存未命中，查数据库
        User user = userMapper.selectById(id);
        if (user != null) {
            redisTemplate.opsForHash().put(key, field, JSON.toJSONString(user));
        }
        return user;
    }
}